const pako = require('pako');
import weappJwt from './base64.js'


function convertTypedArray(src, type) {
	let buffer = new ArrayBuffer(src.byteLength);
	let baseView = new src.constructor(buffer).set(src);
	return new type(buffer);
}

/**
 * 数组改变
 * @param {Object} data 
 */

const conversion = function(data) {	
	let floatArray = new Float64Array(data);
	let uintArray = convertTypedArray(floatArray, Uint8Array);
	let compressed = pako.deflate(uintArray);
	return weappJwt.encode(compressed)
}



let gyrArr = new Array(),
	accArr = new Array(),
	gyrTime = new Array(),
	accTime = new Array();

let a=0,g=0;

// 打开仪器

const start = function(e) {
	gyrArr = new Array();
	accArr = new Array();
	gyrTime = new Array();
	accTime = new Array();
	
	setTimeout(() => {
		uni.onGyroscopeChange((res) => {
			e(res.x)
			gyrTime.push(new Date().getTime());		
			gyrArr = [].concat(gyrArr,[new Date().getTime(),res.x,res.y,res.z]);
		});
		uni.onAccelerometerChange((res)=>{
			accTime.push(new Date().getTime());
			accArr = [].concat(accArr, [new Date().getTime(), res.x, res.y, res.z]);
		});
	}, 100)
	uni.startGyroscope({
		interval: "game",
		success(res) {
			console.log(res, 'Gyroscope success')
		},
		fail(err) {
			console.log(err, 'Gyroscope fail')
		}
	})
	uni.startAccelerometer({
		interval: "game",
		success(res) {
			console.log(res, 'Accelerometer success')
		},
		fail(err) {
			console.log(err, 'Accelerometer fail')
		}
	});
}

const stop = function(e) {
	// console.log('关闭两个仪器');
	Promise.all([stopGyroscope(), stopAccelerometer()])
		.then(res => {
			let data = {
				acc: conversion(accArr),
				acc_stride: 20,
				acc_timestamp: accTime[0],
				gyro: conversion(gyrArr),
				gyro_stride: 20,
				gyro_timestamp: gyrTime[0],
			}
			e(data)
		})
}


const stopGyroscope = function() {
	return new Promise((resolve, reject) => {
		uni.stopGyroscope({
			success(res) {
				uni.offGyroscopeChange()
				console.log(res, 'stop success!');
				resolve()
			},
			fail(err) {
				console.log(err, 'stop fail!')
			}
		})
	})
}

const stopAccelerometer = function() {
	return new Promise((resolve, reject) => {
		uni.stopAccelerometer({
			success(res) {
				console.log(res, 'stop success!');
				uni.offAccelerometerChange()
				resolve()
			},
			fail(err) {
				console.log(err, 'stop fail!')
			}
		})
	})
}


export default {
	start,
	stop
}
